<?php

namespace App\Services\Index;

use App\Constants\CodeData;
use App\Dao\AppUpgradeDao;
use App\Dao\ClosenessDao;
use App\Dao\GiftDao;
use App\Dao\IndexActionDao;
use App\Dao\UserDao;
use App\Model\User;
use App\Model\UserSetting;
use App\Utils\FunUtil;
use Hyperf\Context\Context;
use function Hyperf\Translation\trans;

class HomeService
{

    /**
     * Note - 客户端首页用户列表接口
     * DateTime 2024/8/13 12:00
     * User Admin
     * @param array $all
     * @param mixed $userInfo
     * @return array
     */
    public function userList(array $all, mixed $userInfo)
    {
        $uid = $userInfo['id'];
        $page = $all['page'] ?? 1;
        $from = $all['from'];
        $version_code = $all['version_code'];
        $channel = $all['channel'];
        $type = $all['type'] ?? 1;
        $language = Context::get('language', 'en');
        $filter = isset($all['filter']) ? json_decode($all['filter']) : [];
        // $filter = !empty($base64Filter) ? json_decode(base64_decode($base64Filter), true) : [];
        // $filter = [
        //     'auth_type' => "真人认证",    //0不限 1真人认证 2实名认证
        //     'location' => "广东省-广州市",   // 所在地
        //     'age' => '20岁~60岁',    //年龄
        //     'height' => '175cm~180cm',   // 身高
        //     'weight' => "58kg~68kg", // 体重
        //     'education' => '大专'  // 学历
        // ];

        $cb = [];
        $cb['msg'] = [];

        if (empty($userInfo)) {
            $cb['result'] = 2;
        } else {
            $indexAction = IndexActionDao::getInstance();
            $cb['result'] = 1;
            $size = 20;

            $appUpgrade = new AppUpgradeDao();
            $userModel = new UserDao();
            if ($appUpgrade->isHideMaleChatCost($from, $version_code, $channel, FunUtil::getClientIp(), $uid)) {
                $loadUserList = $indexAction->idleUserList($language, $type, $userInfo, $page, $size);
            } else {
                $loadUserList = $indexAction->recommendUserList($version_code, $language, $type, $uid, $userInfo["sex"], $userInfo["gift_count"], $page, $size, false, 0, $filter, $userInfo['province']);
                if (sizeof($loadUserList) <= 0 && $type == 1 && empty($filter)) {
                    $loadUserList = $indexAction->recommendUserList($version_code, $language, $type, $uid, $userInfo["sex"], $userInfo["gift_count"], $page, $size, true);
                }
            }

            $loadUids = array_column($loadUserList, "id");
            $loadUids = empty($loadUids) ? [1] : $loadUids;
            $tease_arr = $userModel->readTease($loadUids, $uid);
            $cArr = ClosenessDao::getMyCloseness($uid, $userInfo['sex'], $loadUids);
            // 用户位置显示开关
            $userSetting = UserSetting::query()->select(['uid', 'show_addr'])->whereIn('uid', $loadUids)->get()->toArray();
            $showAddr = empty($userSetting) ? [] : array_column($userSetting, 'show_addr', 'uid');

            $channelArr = ['xy_oppo', 'xy_vivo', 'xy_bd'];
            foreach ($loadUserList as $key => &$user) {
                $user['is_tease'] = isset($tease_arr[$user['id']]) ? 1 : 0;
                if ((isset($cArr[$user['id']]) && $cArr[$user['id']] > 0)) {
                    $user['is_tease'] = 1;
                }
                if ($userInfo['sex'] == 2 && $user['login_time'] >= time() - 600) {
                    $user['is_tease'] = 1;
                }

                if (isset($showAddr[$user['id']]) && $showAddr[$user['id']] >= 0) {
                    $user['show_addr'] = $showAddr[$user['id']];
                } else {
                    $user['show_addr'] = $user['sex'] == 1 ? 1 : 0;
                }

                // 判断oppo、vivo渠道不能被搭讪
                if (in_array($user['channel'], $channelArr) || in_array($user['ext_channel'], $channelArr)) {
                    $user['is_tease'] = 1;
                }

                //去掉昵称与id相同的
                if ($user['nickname'] == $user['id']) {
                    unset($loadUserList[$key]);
                }

                // 用户隐藏通话状态
                if ($user['hide_call_status'] && $user['online'] == 2) {
                    $user['online'] = 1;
                }
            }
            $loadUserList = array_values($loadUserList);
            $cb['msg'] = $loadUserList;
        }
        return formatData($cb);
        // Tool::JSON(200, $cb, 'success');
    }


    /**
     * Note - 首页搜索接口
     * DateTime 2024/8/13 11:59
     * User Admin
     * @param mixed $user
     */
    public function userSearch(mixed $userInfo, $params)
    {
        $keyword = $params['keyword'] ?? ''; // 关键词
        $uid = intval($params['uid'] ?? 0);
        $language = $params['language'];
        $page = $params['page'];
        $cb['result'] = 0;
        $cb['msg'] = [];
        if (intval($keyword) == $uid) {
            // Tool::JSON(\CodeData::NEED_TIPS, null, '没有符合您要求的人');
            return formatData($cb, 200, CodeData::NEED_TIPS, '没有符合您要求的人');
        }
        $indexAction = IndexActionDao::getInstance();

        $loadUserList = $indexAction->SearchUserListPage($userInfo['sex'], $keyword, $page, $params);
        if (empty($loadUserList)) {
            return formatData($cb, 200, CodeData::NEED_TIPS, '没有符合您要求的人');
        } else {
            $cb['result'] = 1;
            foreach ($loadUserList as $k => $vo) {
                $ext = json_decode($vo['ext'], true);
                $loadUserList[$k]['ext'] = $ext;
                $job = $ext['job'] ?? '';
                if (!empty($job)) {
                    $informationArr = trans('information', [], $language);
                    $loadUserList[$k]['job'] = $informationArr['job'][$job]['name'] ?? '';
                } else {
                    $loadUserList[$k]['job'] = '';
                }
                $loadUserList[$k]['weight'] = isset($ext['weight']) && (string)$ext['weight'] != "" ? $ext['weight'] . 'kg' : '60kg';
                $loadUserList[$k]['constellation'] = isset($ext['constellation']) && (string)$ext['constellation'] != "" ? trans('constellation.' . $ext['constellation'], [], $language) : '';
                // 用户隐藏通话状态
                if ($vo['hide_call_status'] && $vo['online'] == 2) {
                    $loadUserList[$k]['online'] = 1;
                }
            }
            $cb['msg'] = $loadUserList;
            return formatData($cb);
        }
        // Tool::JSON(\CodeData::SUCCESS, $cb);
    }


    /**
     * Note - 首页礼物飘窗数据接口
     * DateTime 2024/8/13 16:36
     * User Admin
     * @param mixed $user
     */
    public function giftShow(mixed $user, $params)
    {
        $uid = $user['id'];
        $language = $params['language'];
        $end_time = $params['end_time'];
        $result = GiftDao::getInstance()->getGiftShowList($end_time);
        $uids = array_column($result, 'uid'); // 送礼人id
        $userIds = array_column($result, 'user_id'); // 收礼人id
        $uHides = [];
        if (!empty($uids)) {
            $user_ids = array_merge($uids, $userIds);
            $uHides = UserSetting::query()->select(['uid', 'hidden_nick'])->whereIn('uid', $user_ids)->pluck('hidden_nick', 'uid')->toArray();
        }

        foreach ($result as &$item) {
            if ($item['uid'] != $uid && (!isset($uHides[$item['uid']]) || $uHides[$item['uid']] == 1)) {
                $item['head_image'] = 'https://magoo.oss-ap-southeast-1.aliyuncs.com/default/default/headimg/mysterious.png';
                $item['user_nickname'] = trans('message.神秘人', [], $language);
            }

            if ($item['user_id'] != $uid && (!isset($uHides[$item['user_id']]) || $uHides[$item['user_id']])) {
                $item['user_head_image'] = 'https://magoo.oss-ap-southeast-1.aliyuncs.com/default/default/headimg/mysterious.png';
                $item['user_nickname'] = trans('message.神秘人', [], $language);
            }

            if ($language == 'zh-hk') {
                $item['gift_name'] = $item['gift_hk_name'];
            } else {
                $item['gift_name'] = $item['gift_en_name'];
            }
            unset($item['gift_hk_name']);
            unset($item['gift_en_name']);

            $item['wait'] = intval($item['wait']);
            $item['notice_type'] = intval($item['notice_type']);
            $item['sub_type'] = intval($item['sub_type']);
        }

        array_unshift($result, [
            "uid" => "10000",
            "notice_type" => 2,
            "nickname" => trans('message.神秘人', [], $language),
            "head_image" => "https://magoo.oss-ap-southeast-1.aliyuncs.com/default/default/headimg/mysterious.png",
            "sex" => 1,
            "user_nickname" => trans('message.神秘人', [], $language),
            "user_head_image" => "https://magoo.oss-ap-southeast-1.aliyuncs.com/default/default/headimg/mysterious.png",
            "user_sex" => 2,
            "user_id" => "10000",
            "img" => "https://magoo.oss-ap-southeast-1.aliyuncs.com/gift/加冕.png",
            "name" => trans('message.宠上天', [], 'zh_cn'),
            'hk_name' => trans('message.宠上天', [], 'zh_hk'),
            'en_name' => trans('message.宠上天', [], 'en'),
            "num" => 1,
            "wait" => 3,
            "sub_type" => 1
        ]);

        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $result), '操作成功');
        return formatData(['result' => 1, 'msg' => $result]);
    }


    /**
     * Note - 获取匹配头像（10秒/次，连续30秒没有就返回）
     * DateTime 2024/8/19 17:42
     * User Admin
     * @param mixed $userInfo
     * @return array
     */
    public function getSpeedHead(mixed $userInfo)
    {
        $sex = $userInfo['sex'] == 1 ? 2 : 1;
        $times = strtotime("-3 days");
        $headImgs = User::query()->select('id', 'nickname', 'head_image')
            ->where('head_image_status', 3)
            ->where('sex', $sex)
            ->where('click_time', '>', $times)
            ->orderByRaw('FIELD(online, 1, 2, 0), rand()')
            ->take(5)
            ->get()->toArray();
        // \Tool::JSON(\CodeData::SUCCESS, ['result' => 1, 'msg' => $headImgs], 'success');
        return formatData(['result' => 1, 'msg' => $headImgs]);
    }


}